<template>
  <div class="user-manage">
    <div class="query-form">
      <el-form :model="user" inline ref="form">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="user.userId" placeholder="请输入用户ID"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input
            v-model="user.userName"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户状态" prop="state">
          <el-select v-model="user.state">
            <el-option :value="0" label="所有"></el-option>
            <el-option :value="1" label="在职"></el-option>
            <el-option :value="2" label="离职"></el-option>
            <el-option :value="3" label="试用期"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset('form')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="base-table">
      <div class="table-btn">
        <el-button v-has="'user-add'" type="primary" @click="handleAddUser"
          >新增</el-button
        >
        <el-button
          type="danger"
          v-has="'user-parse-delete'"
          @click="handlePatchDelete"
          >批量删除</el-button
        >
      </div>
      <el-table
        :data="userList"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          v-for="(item, index) in column"
          :key="index"
          :prop="item.prop"
          :label="item.label"
          :width="item.width"
          :formatter="item.formatter"
        />
        <el-table-column label="操作" width="300">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="handleEdit(scope.row)"
              v-has="'user-edit'"
              >编辑</el-button
            >
            <el-button
              size="small"
              type="danger"
              v-has="'user-delete'"
              @click="handleDelete(scope.row.userId)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="pagination"
        background
        layout="prev, pager, next"
        :total="pager.total"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </div>
    <!-- 对话框 -->
    <el-dialog
      v-model="dialogFormVisible"
      :title="action == 'add' ? '新增' : '编辑'"
      :before-close="handleClose"
    >
      <el-form
        label-width="100px"
        :model="userform"
        :rules="rules"
        ref="dialogForm"
      >
        <el-form-item label="用户名" prop="userName">
          <el-input
            placeholder="请输入用户名"
            v-model="userform.userName"
            :disabled="action == 'edit'"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="userEmail">
          <el-input
            placeholder="请输入邮箱"
            v-model="userform.userEmail"
            :disabled="action == 'edit'"
          >
            <template #append>@qq.com</template>
          </el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input
            placeholder="请输入手机号"
            v-model="userform.mobile"
          ></el-input>
        </el-form-item>
        <el-form-item label="岗位" prop="job">
          <el-input placeholder="请输入岗位" v-model="userform.job"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-select v-model="userform.state">
            <el-option :value="1" label="在职"></el-option>
            <el-option :value="2" label="离职"></el-option>
            <el-option :value="3" label="试用期"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="系统角色" prop="roleList">
          <el-select
            placeholder="请选择用户系统角色"
            v-model="userform.roleList"
            multiple
          >
            <el-option
              v-for="(item, index) in roleList"
              :key="index"
              :label="item.roleName"
              :value="item._id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属部门" prop="deptId">
          <el-cascader
            v-model="userform.deptId"
            placeholder="请选择所在部门"
            :options="deptList"
            :props="{ checkStrictly: true, label: 'deptName', value: '_id' }"
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancle">取消</el-button>
          <el-button type="primary" @click="handleConfirm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { onMounted, reactive, ref, getCurrentInstance, toRaw } from "vue";
import utils from "../../utils/utils";
export default {
  name: "User",
  setup() {
    //获取this实例
    const { proxy } = getCurrentInstance();

    //生命周期
    onMounted(() => {
      getUsersList();
      getRoleList();
      getDeptList();
    });

    // 获取用户列表
    const getUsersList = async () => {
      let param = { ...user, ...pager };
      const { page, list } = await proxy.$api.getUsersList(param);
      // userList.arr = list;
      userList.value = list;
      pager.total = page.total;
    };

    // 查询用户数据
    const handleQuery = () => {
      getUsersList();
    };

    // 重置查询
    const handleReset = (form) => {
      proxy.$refs[form].resetFields();
    };

    // 处理分页变化
    const handleCurrentChange = (current) => {
      pager.pageNum = current;
      getUsersList();
    };

    // 取消编辑
    const handleCancle = () => {
      dialogFormVisible.value = false;
      handleReset("dialogForm");
    };

    // 确认编辑
    const action = ref("add");
    const handleConfirm = () => {
      proxy.$refs.dialogForm.validate(async (valid) => {
        if (valid) {
          let params = toRaw(userform);
          params.userEmail += "@qq.com";
          params.action = action.value;
          let res = await proxy.$api.usersOperate(params);
          if (res) {
            dialogFormVisible.value = false;
            proxy.$message.success(
              action.value == "add" ? "新增用户成功" : "编辑用户成功"
            );
            handleReset("dialogForm");
            getUsersList();
          }
        }
      });
    };

    // 点击删除单个用户
    const handleDelete = async (userId) => {
      const res = await proxy.$api.deleteUser({ userIds: [userId] });

      if (res.modifiedCount > 0) {
        proxy.$message.success(`成功删除${res.modifiedCount}条数据！`);
        getUsersList();
      } else {
        proxy.$message.error(`删除失败！`);
      }
    };

    // 点击删除多个用户
    const checkedUsersIds = ref([]);
    const handlePatchDelete = async () => {
      if (checkedUsersIds.value.length == 0) {
        proxy.$message.error("请选择要删除的用户");
        return;
      }
      const res = await proxy.$api.deleteUser({
        userIds: checkedUsersIds.value,
      });
      if (res.modifiedCount > 0) {
        proxy.$message.success(`成功删除${res.modifiedCount}条数据！`);
        getUsersList();
      } else {
        proxy.$message.error(`成功失败！`);
      }
    };

    const handleSelectionChange = (list) => {
      let arr = [];
      list.forEach((element) => {
        arr.push(element.userId);
      });
      checkedUsersIds.value = arr;
    };

    // 新增用户
    const dialogFormVisible = ref(false);
    const handleAddUser = () => {
      action.value = "add";
      dialogFormVisible.value = true;
    };

    /**数据定义 */
    const user = reactive({
      state: 1,
    }); //引用数据类型
    // const userList = reactive({
    //   arr:[]
    // }); //引用数据类型
    const userList = ref([]); //引用数据类型

    const column = reactive([
      {
        label: "用户ID",
        prop: "userId",
      },
      {
        label: "用户名",
        prop: "userName",
      },
      {
        label: "用户邮箱",
        prop: "userEmail",
      },
      {
        label: "用户角色",
        prop: "role",
        formatter(row, column, value) {
          return {
            0: "管理员",
            1: "普通用户",
          }[value];
        },
      },
      {
        label: "用户状态",
        prop: "state",
        formatter(row, column, value) {
          return {
            1: "在职",
            2: "离职",
            3: "试用期 ",
          }[value];
        },
      },
      {
        label: "注册时间",
        prop: "createTime",
        formatter(row, column, value) {
          return utils.formateDate(new Date(value));
        },
      },
      {
        label: "最后登录时间",
        prop: "lastLoginTime",
        formatter(row, column, value) {
          return utils.formateDate(new Date(value));
        },
      },
    ]);
    const pager = reactive({
      pageNum: 1,
      pageSize: 10,
      total: 10,
    });
    const rules = reactive({
      userName: [
        {
          required: true,
          message: "请输入用户名称",
          trigger: "blur",
        },
      ],
      userName: [
        {
          required: true,
          message: "请输入用户名称",
          trigger: "blur",
        },
      ],
      userEmail: [
        {
          required: true,
          message: "请输入邮箱",
          trigger: "blur",
        },
      ],
      deptId: [
        {
          required: true,
          message: "请选择部门",
          trigger: "change",
        },
      ],
      mobile: [
        {
          required: true,
          message: "请输入正确的手机格式",
          trigger: "blur",
          pattern: /1[3-9]\d{9}/,
        },
      ],
    });

    const userform = reactive({
      state: 1,
    });

    const roleList = ref([]);
    const getRoleList = async () => {
      const res = await proxy.$api.getAllRoleList();
      roleList.value = res;
    };

    const deptList = ref([]);
    const getDeptList = async () => {
      const res = await proxy.$api.getDeptList();
      deptList.value = res;
    };

    const handleEdit = async (row) => {
      dialogFormVisible.value = true;
      action.value = "edit";
      proxy.$nextTick(() => {
        Object.assign(userform, row);
      });
    };

    const handleClose = () => {
      handleReset("dialogForm");
      dialogFormVisible.value = false;
    };

    return {
      user,
      userList,
      column,
      pager,
      checkedUsersIds,
      dialogFormVisible,
      userform,
      rules,
      handleQuery,
      handleReset,
      handleCurrentChange,
      handleDelete,
      handlePatchDelete,
      handleSelectionChange,
      handleAddUser,
      roleList,
      deptList,
      getRoleList,
      getDeptList,
      handleCancle,
      handleConfirm,
      handleEdit,
      action,
      handleClose,
    };
  },
};
</script>

<style>
.table-btn {
  padding: 20px;
}
</style>